//
//  BaseViewController.m
//  ProjectB_
//
//  Created by dllo on 16/3/21.
//  Copyright © 2016年 项目B. All rights reserved.
//

#import "BaseViewController.h"  //C
#import "SDP_PlayerViewController.h"

#import "EveryDayModel.h"   //M
#import "LWH_EveryDayModelForSection.h"

#import "EveryDayTableViewCell.h"   //V
#import "ContentScrollView.h"
#import "ContentView.h"
#import "rilegouleView.h"
#import "CustomView.h"
#import "ImageContentView.h"
#import "LWH_ViewForEveryDaySectionHeader.h"







@interface BaseViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray *arrayForCellData;

@property (nonatomic, strong) NSMutableArray *arrayForSectionData;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) CBStoreHouseRefreshControl *storeHouseRefreshControl; //下拉刷新控件

@property (nonatomic, strong) UIView *viewForBg;    //这三个控件都是监听进度的
@property (nonatomic, strong) UILabel *labelForKVO;
@property (nonatomic, strong) UIView *viewForKVO;

@property (nonatomic, strong) UILabel *labelForNextPublishTime; //下一次更新的时间戳



@end

@implementation BaseViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
   // self.automaticallyAdjustsScrollViewInsets = NO;

    [self handleData];
    
    [self createTableView];
    
    [self settingsNavigationController];
    //1459180800000
    
//    NSDate *date = [NSDate dateWithTimeIntervalSince1970:1459180800];
//    NSLog(@"是多少: %@", date);
//    NSDate *currentData = [NSDate date];
//    NSTimeInterval temp = [currentData timeIntervalSince1970];
//    NSLog(@"当前时间戳:%lf", temp);
//    float aaa = 1459180800 - temp;
//    NSLog(@"时间差:%f", aaa);
    
    //    //用于格式化NSDate对象
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //    //设置格式：zzz表示时区
    //    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
    //    //NSDate转NSString
    //    NSString *currentDateString = [dateFormatter stringFromDate:date];
    //    //输出currentDateString
    //    NSLog(@"%@",currentDateString);

  
}



- (void)settingsNavigationController {
    
    self.labelForNextPublishTime = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, self.view.frame.size.width - 100, 35)];
    self.labelForNextPublishTime.backgroundColor = [UIColor redColor];
    self.labelForNextPublishTime.textAlignment = 1;
    self.navigationItem.titleView = self.labelForNextPublishTime;
    self.labelForNextPublishTime.font = [UIFont systemFontOfSize:13];
    
    
    
}

- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerClass:[EveryDayTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[LWH_ViewForEveryDaySectionHeader class] forHeaderFooterViewReuseIdentifier:@"viewForSectionHeader"];
    
#warning 下拉刷新有问题
    self.storeHouseRefreshControl = [CBStoreHouseRefreshControl attachToScrollView:self.tableView target:self refreshAction:@selector(refreshTriggered:) plist:@"AKTA" color:[UIColor redColor] lineWidth:3 dropHeight:50 scale:1 horizontalRandomness:150 reverseLoadingAnimation:NO internalAnimationFactor:1];
}
- (void)refreshTriggered:(id)sender {
    
    [self performSelector:@selector(afreshAction) withObject:nil afterDelay:2];
    
    
}

- (void)afreshAction {
    [self handleData];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    
    return self.arrayForSectionData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    return [[self.arrayForCellData objectAtIndex:section] count];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return nil;
    }
    
    LWH_ViewForEveryDaySectionHeader *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"viewForSectionHeader"];
    [view passData:[self.arrayForSectionData objectAtIndex:section - 1]];
    view.contentView.backgroundColor = [UIColor whiteColor];
    return view;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EveryDayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return kHeight / 3;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }
    LWH_EveryDayModelForSection *model = [self.arrayForSectionData objectAtIndex:section];
    if ([model.type isEqualToString:@"image"]) {
        return 70;
    }
    return 50;
}

//添加每个cell出现时的3D动画
-(void)tableView:(UITableView *)tableView willDisplayCell:(EveryDayTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //        CATransform3D rotation;//3D旋转
    //
    //        rotation = CATransform3DMakeTranslation(0 ,50 ,20);
    ////        rotation = CATransform3DMakeRotation( M_PI_4 , 0.0, 0.7, 0.4);
    //        //逆时针旋转
    //
    //        rotation = CATransform3DScale(rotation, 0.9, .9, 1);
    //
    //        rotation.m34 = 1.0/ -600;
    //
    //        cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    //        cell.layer.shadowOffset = CGSizeMake(10, 10);
    //        cell.alpha = 0;
    //
    //        cell.layer.transform = rotation;
    //
    //        [UIView beginAnimations:@"rotation" context:NULL];
    //        //旋转时间
    //        [UIView setAnimationDuration:0.6];
    //        cell.layer.transform = CATransform3DIdentity;
    //        cell.alpha = 1;
    //        cell.layer.shadowOffset = CGSizeMake(0, 0);
    //        [UIView commitAnimations];
    
    
    [cell cellOffset];
    
    EveryDayModel *model = [[self.arrayForCellData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    [cell setModel:model];
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self showImageAtIndexPath:indexPath];
}


#pragma mark - 设置详情界面
- (void)showImageAtIndexPath:(NSIndexPath *)indexPath{
    
    _array = [self.arrayForCellData objectAtIndex:indexPath.section];
    
    _currentIndexPath = indexPath;
    
    EveryDayTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    CGRect rect = [cell convertRect:cell.bounds toView:nil];
    CGFloat y = rect.origin.y;
    
    _rilegoule = [[rilegouleView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) imageArray:_array index:indexPath.row];
    _rilegoule.offsetY = y;
    _rilegoule.animationTrans = cell.picture.transform;
    _rilegoule.animationView.picture.image = cell.picture.image;
    
    _rilegoule.scrollView.delegate = self;
    
    [[self.tableView superview] addSubview:_rilegoule];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"隐藏" object:nil];
    
    //添加轻扫手势
    UISwipeGestureRecognizer *Swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    
    _rilegoule.contentView.userInteractionEnabled = YES;
    
    Swipe.direction = UISwipeGestureRecognizerDirectionUp;
    
    [_rilegoule.contentView addGestureRecognizer:Swipe];
    
    //添加点击播放手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [_rilegoule.scrollView addGestureRecognizer:tap];
    
    [_rilegoule aminmationShow];
    
    //详情页的位置KVO
    
    self.viewForBg = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 5 * indexPath.row, self.view.frame.size.height - 30, self.view.frame.size.width / 5, 30)];
    [_rilegoule addSubview:self.viewForBg];
    self.viewForBg.backgroundColor = [UIColor clearColor];
    
    self.labelForKVO = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 5, 28)];
    [self.viewForBg addSubview:self.labelForKVO];
    self.labelForKVO.textColor = [UIColor whiteColor];
    self.labelForKVO.textAlignment = 1;
    NSString *str = [NSString stringWithFormat:@"%ld-%ld", indexPath.row + 1, _array.count];
    self.labelForKVO.text = str;
    self.labelForKVO.alpha = 0;
    
    self.viewForKVO = [[UIView alloc] initWithFrame:CGRectMake(0, 29, self.view.frame.size.width / 5, 1)];
    self.viewForKVO.backgroundColor = [UIColor whiteColor];
    [self.viewForBg addSubview:self.viewForKVO];
    self.viewForKVO.alpha = 0;
    
    [UIView animateWithDuration:1 animations:^{
        self.labelForKVO.alpha = 1;
        self.viewForKVO.alpha = 1;
    }];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    

    if ([scrollView isEqual:_rilegoule.scrollView]) {
        
        if (self.viewForKVO != nil && self.labelForKVO != nil && self.viewForBg != nil) {
            
            self.viewForBg.frame = CGRectMake(self.view.frame.size.width / 5 * 4 / (_array.count - 1) * scrollView.contentOffset.x / self.view.frame.size.width, self.view.frame.size.height - 30, self.view.frame.size.width / 5, 30);
            
            
        }
        for (ImageContentView *subView in scrollView.subviews) {
            
            if ([subView respondsToSelector:@selector(imageOffset)] ) {
                [subView imageOffset];
            }
        }
        
        CGFloat x = _rilegoule.scrollView.contentOffset.x;
        
        CGFloat off = ABS( ((int)x % (int)kWidth) - kWidth/2) /(kWidth/2) + .2;
        
        [UIView animateWithDuration:1.0 animations:^{
            _rilegoule.playView.alpha = off;
            _rilegoule.contentView.titleLabel.alpha = off + 0.0;
            _rilegoule.contentView.littleLabel.alpha = off + 0.0;
            _rilegoule.contentView.lineView.alpha = off + 0.0;
            _rilegoule.contentView.descripLabel.alpha = off + 0.0;
            _rilegoule.contentView.collectionCustom.alpha = off + 0.0;
            _rilegoule.contentView.shareCustom.alpha = off + 0.0;
            _rilegoule.contentView.cacheCustom.alpha = off + 0.0;
            _rilegoule.contentView.replyCustom.alpha = off + 0.0;
            
        }];
        
    } else {
        
        NSArray<EveryDayTableViewCell *> *array = [self.tableView visibleCells];
        
        [array enumerateObjectsUsingBlock:^(EveryDayTableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [obj cellOffset];
        }];
        
    }
    
    [self.storeHouseRefreshControl scrollViewDidScroll];
    
}

// 拖拽将要结束(下拉刷新)
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
     [self.storeHouseRefreshControl scrollViewDidEndDragging];
    
}


// 滑动将要结束
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    
    if ([scrollView isEqual:_rilegoule.scrollView]) {
        
        int index = floor((_rilegoule.scrollView.contentOffset.x - scrollView.frame.size.width / 2) / scrollView.frame.size.width) + 1;
        
        NSLog(@"左右滑动");
        
        _rilegoule.scrollView.currentIndex = index;
        
        NSString *str = [NSString stringWithFormat:@"%d-%ld", index + 1, _array.count];
        self.labelForKVO.text = str;
        
        self.currentIndexPath = [NSIndexPath indexPathForRow:index inSection:self.currentIndexPath.section];
        
        [self.tableView scrollToRowAtIndexPath:self.currentIndexPath atScrollPosition:(UITableViewScrollPositionMiddle) animated:NO];
        
        [self.tableView setNeedsDisplay];
        EveryDayTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.currentIndexPath];
        
        [cell cellOffset];
        
        CGRect rect = [cell convertRect:cell.bounds toView:nil];
        _rilegoule.animationTrans = cell.picture.transform;
        _rilegoule.offsetY = rect.origin.y;
        
        EveryDayModel *model = _array[index];
        
        [_rilegoule.contentView setData:model];
        
        [_rilegoule.animationView.picture sd_setImageWithURL:[NSURL URLWithString:[model.cover objectForKey:@"feed"]] placeholderImage:nil];
        
    }
    
    
}

#pragma mark - 平移手势触发事件
- (void)panAction:(UISwipeGestureRecognizer *)swipe{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"显示" object:nil];
    [_rilegoule animationDismissUsingCompeteBlock:^{
        
        _rilegoule = nil;
        self.viewForBg = nil;
        self.viewForKVO = nil;
        self.labelForKVO = nil;
    }];
    
}

#pragma mark - 点击手势
- (void)tapAction{


    SDP_PlayerViewController *playerVC = [[SDP_PlayerViewController alloc]init];

    playerVC.indexForMovie = self.currentIndexPath.row;
    playerVC.modelArray = self.array;
    
    [self presentViewController:playerVC animated:YES completion:nil];
    
    
}

#pragma mark - 数据解析
- (void)handleData {
    
    // 每日精选接口
    [NetWorkHandler networkingWithUrl:self.url comleteHandle:^(id result, NSData *data) {
        
        self.arrayForCellData = [NSMutableArray array];
        self.arrayForSectionData = [NSMutableArray array];
        
        self.nextPublishTime = [result objectForKey:@"nextPublishTime"];
        
        NSArray *arrayForIssueList = [result objectForKey:@"issueList"];
        
        for (NSDictionary *dic1 in arrayForIssueList) {
            NSArray *arrForItemList = [dic1 objectForKey:@"itemList"];
            
            NSMutableArray *arrayForTemp = [NSMutableArray array];
            for (NSDictionary *dic2 in arrForItemList) {
                
                
                NSString *type = [dic2 objectForKey:@"type"];
                NSDictionary *dicForData = [dic2 objectForKey:@"data"];
                
                if (![type isEqualToString:@"video"]) {
                    LWH_EveryDayModelForSection *model = [[LWH_EveryDayModelForSection alloc] init];
                    [model setValuesForKeysWithDictionary:dic2];
                    [model setValuesForKeysWithDictionary:dicForData];
                    [self.arrayForSectionData addObject:model];
                } else {
                    EveryDayModel *model = [[EveryDayModel alloc] init];
                    [model setValuesForKeysWithDictionary:dicForData];
                    [arrayForTemp addObject:model];
                }
                
            }
            [self.arrayForCellData addObject:arrayForTemp];
            
        }
        NSLog(@"下一次更新的时间戳:%@", self.nextPublishTime);
        self.url = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v2/feed?_s=e48de6c45c4b5696bf50bb93efb030f1&date=%@&f=iphone&net=wifi&num=7&u=693b683a5db7a43954ed61f0fad8d5f216b94455&v=1.12.1&vc=403", self.nextPublishTime];
        [self.tableView reloadData];
         [self.storeHouseRefreshControl finishingLoading];
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
